unit Debug;

interface

uses
  SysUtils,
  Head;

const
  Game_OK = 0;
  Debug_Enable = true;

type
  TDebug = class
  const
    OriDebugFileName = 'Debug.txt';
  var
    Filename: String;
    NextLine: Cardinal;
    constructor Create;
    destructor Destroy; override;
    procedure AddDebugInfo(str: String);
  end;

var
  GameDebug: TDebug;

implementation

constructor TDebug.Create;
var
  FH: integer;
  UnicodeTxtHead: Word;
begin
  inherited;
  Filename := OriDebugFileName;
  Filename := ExtractFilePath(ParamStr(0)) + Filename;
  try
    if not Debug_Enable then
      exit;
    if not CanDebug then
      exit;
    DeleteFile(Filename);
    FH := FileCreate(Filename);
    UnicodeTxtHead := $FEFF;
    FileWrite(FH, UnicodeTxtHead, 2);
    FileClose(FH);
    NextLine := $A000D;
    //CanDebug := true;
    AddDebugInfo('Debug Start!');
  except
    CanDebug := false;
  end;
end;

procedure TDebug.AddDebugInfo(str: String);
var
  tempstr, DebugDateTime: widestring;
  t: UTF8String;
  FH: integer;
begin
  //
  if ConsoleMode then
    Writeln(StrToAnsi(str));
  if not Debug_Enable then
    exit;
  if not CanDebug then
    exit;
  DebugDateTime := UTF8Decode(DateTimetoStr(Date+Time));
  tempstr := DebugDateTime + ': ' + UTF8Decode(str);
  if fileexists(Filename) then
  begin
    FH := Fileopen(Filename, fmopenreadwrite);
    Fileseek(FH, 0, 2);
    FileWrite(FH, tempstr[1], length(tempstr) * sizeof(wideChar));
    FileWrite(FH, NextLine, 4);
    Fileclose(FH);
  end;
end;

destructor TDebug.Destroy;
begin
  AddDebugInfo('Debug End!');
  CanDebug := false;
  inherited Destroy;
end;

end.
